package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.SupplyInventoryView;
import Models.WarehouseInventory;

public class WarehouseInventoryPresenter extends AbstractPresenter<WarehouseInventory> {
	final String SINGLEITEM = "supplyInventory";
	final String MULTIITEM = "supplyInventories";
	
	public ArrayList<WarehouseInventory> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public WarehouseInventory tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public WarehouseInventory createItemFromJSONObject(JSONObject jsonObject){
		WarehouseInventory item = new WarehouseInventory();
		try{
			item.setWarehouseId(jsonObject.getInt("warehouseId"));
			item.setWarehouseName(jsonObject.getString("warehouseName"));
			
			//Set Documents Collection
			ArrayList<SupplyInventoryView> items = new ArrayList<SupplyInventoryView>();
			if(!jsonObject.isNull("supplyCollection")){
				Object itm = jsonObject.get("supplyCollection");
				SupplyInventoryViewPresenter presenter = new SupplyInventoryViewPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						items.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					items.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setSupplyCollection(items);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(WarehouseInventory item){
		try{
			JSONObject json = new JSONObject();
			json.put("warehouseId", item.getWarehouseId());
			json.put("warehouseName", item.getWarehouseName());
			
			//Create Doc Collection
			if(item.getSupplyCollection()!=null){
				SupplyInventoryViewPresenter presenter = new SupplyInventoryViewPresenter();
				if(item.getSupplyCollection().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getSupplyCollection().size(); i++){
						jsonArray.put(presenter.createJSON(item.getSupplyCollection().get(i)));
					}
					json.put("supplyCollection", jsonArray);
				}
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public WarehouseInventory getEmptyEntity(){
		WarehouseInventory entity = new WarehouseInventory();
		return entity;
	}
}
